import { observable, action } from 'mobx';
import * as Apis from "../../api/customerApis";
import * as adapter from '../../constants/adapter';
import { Toast, Bubble, Tools } from 'weaver-mobile';
import { BrowserHrm, ListViewPage, RouteLayout, MapPage, Form } from 'weaver-mobile-page';
const getLabel = Tools.getLabel;

const addressTemp = ['country', 'province', 'city', 'district'];
const addressNumbers = {
    'country': 258,
    'province': 2222,
    'city': 58,
    'district': 263
}

export default class CustomerViewAndEditStore {

    comObj = {};
    @observable viewForm = {};
    @observable editForm = {};
    @observable customerId = "";
    @observable canEdit = false;//能否编辑
    @observable isFormInit = false;//是否获取到表单
    @observable isViewForm = false;//获取到查看
    @observable isEditForm = false;//获取到编辑
    @observable isDeleted = false;//是否删除成功
    @observable initSuccessed = false;
    @observable initFailedMsg = "";
    @observable showMap = false;
    @observable lat = 0;
    @observable lng = 0;
    @observable hasPosition = false;
    @observable changeLocalLayout = {};
    @observable buttonProps = { loading: false, disabled: false };
    @observable params = {};
    DoNew = (param, comObj) => {
        this.params = param;
        this.comObj = comObj;
        this.customerId = param.id;
    }

    @action
    doInit = () => {
        const param = { isView: true,customerId: this.customerId,...this.params};
        Apis.customerView(param).then(data => {
            this.doInitCallBack(data);
        })
    }

    @action
    doInitCallBack = (data) => {
        const currentPath = this.comObj.props.location.pathname;
        this.isFormInit = true;
        if (data.status === "success") {
            this.viewForm = new Form.Store(currentPath);
            this.viewForm.initForm(data.datas);
            this.isViewForm = true;
            this.initSuccessed = true;
        } else {
            this.initFailedMsg = data.msgcode;
            this.initSuccessed = false;
        }
    }

    //获取编辑表单
    @action
    getEditForm = () => {
        const currentPath = this.comObj.props.location.pathname;
        this.isFormInit = false;
        Apis.customerView({ customerId: this.customerId, isView: false }).then(data => {
            if (data.status === "success") {
                this.editForm = new Form.Store();
                this.editForm.initForm(data.datas, currentPath);


                const countryStore = this.editForm.browsers.country;
                const provinceStroe = this.editForm.browsers.province;
                const cityStore = this.editForm.browsers.city;
                const districtStore = this.editForm.browsers.district;
              
                let  countryStoreIsNotdeFined = typeof(countryStore) != "undefined";
                let  provinceStroeIsNotdeFined = typeof(provinceStroe) != "undefined";
                let  cityStoreIsNotdeFined = typeof(cityStore) != "undefined";
                let  districtIsNotdeFined = typeof(districtStore) != "undefined";

				const counUrl = `/api/public/browser/data/258`;
                const provinceUrl = `/api/public/browser/data/2222`;
                const cityUrl = `/api/public/browser/data/58`;
                const districtUrl = `/api/public/browser/data/263`;
                const {country,province,city,district} = this.editForm.formData  ;

				let isInitEDit = false;

                 if(countryStoreIsNotdeFined&&country.value.length > 0&&country.value[0].id >0){                  
                    isInitEDit = true;                      
                    (typeof(country) != 'undefined')&&provinceStroeIsNotdeFined&&provinceStroe.countryClick(counUrl, {id:country.value[0].id,isParent:true,type:'coun'}, 2222);                              
                }
                if(provinceStroeIsNotdeFined&&province.value.length > 0&&province.value[0].id > 0){ 
                    isInitEDit = true;   
                    (typeof(country) != 'undefined')&&cityStoreIsNotdeFined&&cityStore.countryClick(counUrl, {id:country.value[0].id,isParent:true,type:'coun'}, 2222);
                    (typeof(province) != 'undefined')&&cityStoreIsNotdeFined&&cityStore.provClick(cityUrl, {id:province.value[0].id,isParent:true,type:'prov'}, 258)
                }
                if(cityStoreIsNotdeFined&&city.value.length > 0&&city.value[0].id > 0){
                    isInitEDit = true;   
                    (typeof(country) != 'undefined')&&districtIsNotdeFined&&districtStore.countryClick(counUrl, {id:country.value[0].id,isParent:true,type:'coun'}, 2222);
                    (typeof(province) != 'undefined')&&districtIsNotdeFined&&districtStore.provClick(cityUrl, {id:province.value[0].id,isParent:true,type:'prov'}, 258);
                    districtIsNotdeFined&&districtStore.cityClick(districtUrl, {id:city.value[0].id,isParent:true,type:'city'}, 263);
                }
    
                const newGetDatas = (store) => {
                    if(typeof(store) == "undefined"){
                        return;
                    }
                    const getDatas = store.getDatas;
                    const callApiFun = store.callApiFun;
    
                    store.callApiFun = (url, params, callback) => {
                        const _this = this;
                        const cb = (...args) => {
                            callback(...args);
                            window.__setValue && window.__setValue(_this);
                        }
                        callApiFun(url, params, cb);
                    };
    
                    store.getDatas = function (params = {}, type) {
                        if (params.params && params.params.id < 0 ) {
                            this.loading = false;
                            return;
                        }
						 if(isInitEDit){
                            this.loading = false;
							isInitEDit = false; 
                            return;
                        }
						if(params.params &&params.params.id  == 0){
                            params.params.id = 1;
                        }
                        getDatas(params, type);
                    };
    
                };
                newGetDatas(countryStore);
                newGetDatas(provinceStroe);
                newGetDatas(cityStore);
                newGetDatas(districtStore);
                
                if(countryStoreIsNotdeFined){
                    countryStore.doClear = () => {};
                }
                if(provinceStroeIsNotdeFined){
                    provinceStroe.doClear = () => {};
                }
                if(cityStoreIsNotdeFined){
                    cityStore.doClear = () => {};
                }
                if(districtIsNotdeFined){
                    districtStore.doClear = () => {};
                }


                this.changeLocalLayout = new RouteLayout.Store({ route: currentPath, id: 'changeLocalLayout' });
                this.isViewForm = false;
                this.isEditForm = true;
                this.initSuccessed = true;
                this.lat = data.lat == ""?0:parseFloat(data.lat);
                this.lng = data.lng  == ""?0:parseFloat(data.lng);
                if (this.lat == 0 || this.lng == 0) {
                    this.hasPosition = false;
                } else {
                    this.hasPosition = true;
                    this.showMap = true;
                }
            } else {
                this.initFailedMsg = data.msgcode;
                this.initSuccessed = false;
            }
            this.isFormInit = true;
        })
    }
    //取消编辑
    @action
    cancelEdit = () => {
        this.isFormInit = false;
        this.doInit();
    }
    //保存
    @action
    doSave = () => {
        const params = { ...this.editForm.formParams, customerId: this.customerId, lat1: this.lat, lng1: this.lng };
        if (this.editForm.doValidate().pass) {
            if(params.portalloginid){
                delete params.portalloginid;
            }
            Toast.loading(getLabel('388626', '正在保存，请稍后...'), 0);
            Apis.saveEdit(params).then(data => {
                if (data.status === "success") {
                    Toast.hide();
                    Bubble.success(data.msgcode, 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
                        this.isFormInit = false;
                        this.doInit();
                    });
                } else {
                    Toast.hide();
                    Bubble.error(data.msgcode, 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
                        this.isFormInit = false;
                        this.doInit();
                    });
                }
            });
        }
    }
    //删除客户
    @action
    doDelete = () => {
        const params = { customerIds: this.customerId };
        Apis.crmDelete(params).then(data => {
            if (data.status === "success") {
                Bubble.success(getLabel('83472', '删除成功!'), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
                    this.comObj.props.history.go(-2);
                    if (typeof (this.comObj.props.cardStore !== "undefined") && this.comObj.props.cardStore) {
                        this.comObj.props.cardStore.doInit();
                    }
                }
                );
                window.crmGlobal && window.crmGlobal.doSearch();
            } else {
                Bubble.success(data.msgcode, 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => { });
            }
        });
    }
    @action
    getCurrentPosition1 = (result) => {
        if (typeof (result) === "undefined" || (result.status === "error") || (result.status === -1)) {
        } else {
            this.lng = result.position[0]== ""?0:parseFloat(result.position[0]);
            this.lat = result.position[1] ==""?0:parseFloat(result.position[1]);
            this.showMap = true;
        }
    }
    @action
    getLocation = (data) => {
        //地址
        let address1 = data.address + data.name;
        //省
        let province = "";
        //市
        let city = "";
        //县
        let district = "";

        //定位信息
        // this.position = data.name;
        // this.location = data.location;
        // this.editForm.updateField("address1", address1);云商店组件，之前谷歌地图需要传数值类型的 经纬度，组件
        this.lat = data.location.split(",")[1] == ""?0:parseFloat(data.location.split(",")[1]);
        this.lng = data.location.split(",")[0] == ""?0:parseFloat(data.location.split(",")[0]);

        Tools.callApi(
            {
                url: 'https://restapi.amap.com/v3/geocode/regeo',
                method: 'GET',
                params: {
                    key: "deee9801361e46e9340bd492ae45b90d",
                    location: data.location,
                },
                includeCredentials: false,
            }
        ).then(data => {
            // console.log(data);
            if (data.status == '1') {
                province = data.regeocode.addressComponent.province;
                city = data.regeocode.addressComponent.city;
                district = data.regeocode.addressComponent.district;
                //address1 = (province ? province : "") + (city ? city : "") + (district ? district : "") + address1;
                //以下两个是浏览按钮，特殊处理
                //根据城市名称获取城市id,区县id
                Apis.GetCityId({ district: district, city: city,customerId: this.customerId, lat: this.lat, lng: this.lng}).then(datas => {
                    if (datas.status === "success") {
                        if (datas.cityid !== "") {
                            const updateCity = [{ id: datas.cityid, name: city }];
                            this.editForm.updateField("city", updateCity);
                        }
                        if (datas.districtid !== "") {
                            const updateDistrict = [{ id: datas.districtid, name: datas.districtName }];
                            this.editForm.updateField("district", updateDistrict);
                        }
                        if (datas.provinceid !== "") {
                            const updateProvince = [{ id: datas.provinceid, name: datas.provinceName }];
                            this.editForm.updateField("province", updateProvince);
                        }
                        if (datas.countryid !== "") {
                            const updateCountyr = [{ id: datas.countryid, name: datas.countryName }];
                            this.editForm.updateField("country", updateCountyr);
                        }
                    }
                });
            }
            this.location = data.location;
            this.editForm.updateField("address1", address1);
        })
    }
    @action
    groupToggle = (...arg) => {
        const title = arg[0];
        const status = arg[1];
        this.editForm.conditioninfo = this.editForm.conditioninfo.map(c => ({
            ...c,
            ...(c.title === title ? { show: status } : {}),
        }));
    }
    @action
    setAddressInfo = (type, value) => {
        const v = value.length > 0 ? value[0].id : '';
        if (addressTemp.indexOf(type) > -1) {
            if(!value || value.length <= 0) {
                switch(type) {
                    case 'country': 
                        this.counS = '';
                        break;
                    case 'province':
                        this.provS = '';
                        break;
                    case 'city':
                        this.cityS = '';
                    case 'district':
                        this.districtS = '';
                }
            }

            switch (type) {
                case 'country':
                    if (!v || v !== this.counS) {
                        this.provS = '';
                        this.cityS = '';
                        this.districtS = '';
                    }
                    break;
                case 'province':
                    if (!v || v !== this.provS) {
                        this.cityS = '';
                        this.districtS = '';
                    }
                    break;
                case 'city':
                    if (!v || v !== this.cityS) {
                        this.districtS = '';
                    }
                    break;
            }
            const { editForm, counS, provS, cityS, districtS } = this;
            const { counSelected, countrys, provsSelected, provs, citySelected, citys, districtSelected, districts } = editForm.browsers[type];
            const countryStore = editForm.browsers.country;
            const provinceStroe = editForm.browsers.province;
            const cityStore = editForm.browsers.city;
            const districtStore = editForm.browsers.district;

            let  countryStoreIsNotdeFined = typeof(countryStore) != "undefined";
            let  provinceStroeIsNotdeFined = typeof(provinceStroe) != "undefined";
            let  cityStoreIsNotdeFined = typeof(cityStore) != "undefined";
            let  districtIsNotdeFined = typeof(districtStore) != "undefined";

            const coun = countryStoreIsNotdeFined&&(countrys.length ? countrys : countryStore.countrys).find(c => c.id === (counSelected || counS));
            const prov = provinceStroeIsNotdeFined&&(provs.length ? provs : provinceStroe.provs).find(p => p.id === (provsSelected || provS));
            const city = cityStoreIsNotdeFined&&(citys.length ? citys : cityStore.citys).find(ci => ci.id === (citySelected || cityS));
            const district = districtIsNotdeFined&&(districts.length ? districts : districtStore.districts).find(dis => dis.id === (districtSelected || districtS));
            const counUrl = `/api/public/browser/data/258`;
            const provinceUrl = `/api/public/browser/data/2222`;
            const cityUrl = `/api/public/browser/data/58`;
            const districtUrl = `/api/public/browser/data/263`;


			 if(value.length <= 0){
                if(type == 'country'){
                    provinceStroeIsNotdeFined&&editForm.updateField('province', [{ id: '', name: ''}]);
                    cityStoreIsNotdeFined&&editForm.updateField('city',  [{ id: '', name: ''}]);
                    districtIsNotdeFined&&editForm.updateField('district', [{ id: '', name: ''}]);
                }
                if(type == 'province'){
                    cityStoreIsNotdeFined&&editForm.updateField('city',  [{ id: '', name: ''}]);
                    districtIsNotdeFined&&editForm.updateField('district', [{ id: '', name: ''}]);
                }
                if(type == 'city'){
                    districtIsNotdeFined&&editForm.updateField('district', [{ id:'', name: ''}]);
                }  
                return;
             }

            if (coun) {
                countryStoreIsNotdeFined&&countryStore.countryClick(counUrl, coun, 258);
                provinceStroeIsNotdeFined&&provinceStroe.countryClick(counUrl, coun, 2222);
                cityStoreIsNotdeFined&&cityStore.countryClick(counUrl, coun, 58);
                districtIsNotdeFined&&districtStore.countryClick(counUrl, coun, 263);
            }

            if (prov) {
                countryStoreIsNotdeFined&&countryStore.provClick(provinceUrl, prov, 258);
                provinceStroeIsNotdeFined&&provinceStroe.provClick(provinceUrl, prov, 2222);
                cityStoreIsNotdeFined&&cityStore.provClick(provinceUrl, prov, 58);
                districtIsNotdeFined&&districtStore.provClick(provinceUrl, prov, 263)
            }

            if(city) {
                countryStoreIsNotdeFined&&countryStore.cityClick(cityUrl, city, 258);
                cityStoreIsNotdeFined&&cityStore.cityClick(cityUrl, city, 58);
                districtIsNotdeFined&&districtStore.cityClick(cityUrl, city, 263);
            }

            const setDistrict = (store, type) => {
                store.counSelected = counSelected || (coun && coun.id);
                store.provsSelected = provsSelected || (prov && prov.id);
                store.citySelected = citySelected || (city && city.id);
                store.districtSelected = districtSelected || (district && district.id);
                //countryStoreIsNotdeFined&&countryStore.districtClick(districtUrl, district, type);
            }

            if(district) {
                // setDistrict(countryStore, 258);
                setDistrict(districtStore, 263)
            }

            window.__setValue = (store) => {
                store.counSelected = counSelected || (coun && coun.id);
                store.provsSelected = provsSelected || (prov && prov.id);
                store.citySelected = citySelected || (city && city.id);
                store.districtSelected = districtSelected || (district && district.id);
                window.__setValue = null;
            };
            this.counS = counSelected || (coun && coun.id);
            this.provS = provsSelected || (prov && prov.id);
            this.cityS = citySelected || (city && city.id);
            this.districtS = districtSelected || (district && district.id);
            let flag = true;
            
            if(!this.counS && !this.provS && !this.cityS && !this.districtS) {
                flag = false;
            }
            countryStoreIsNotdeFined&&coun&&editForm.updateField('country', [{ id: this.counS || (flag ? -1 : '' ), name: coun && coun.name }]);
            provinceStroeIsNotdeFined&&prov&&editForm.updateField('province', [{ id: this.provS || (flag ? -1 : ''), name: (prov && prov.name)}]);
            cityStoreIsNotdeFined&&city&&editForm.updateField('city', [{ id: this.cityS || (flag ? -1 : ''), name: (city && city.name) }]);
            districtIsNotdeFined&&editForm.updateField('district', [{ id: this.districtS || (flag ? -1 : ''), name: district && district.name }]);
        }
    }


}